﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPMonitor.Interfaces;
using NPMonitor.DataModel;
using NPMonitor.Implementation;
using NPMonitor.Implementation.Store;
using System.Data.SqlClient;

namespace NPMonitor.InternalJobs
{
    public class HeartbeatJob : IHeartbeat
    {
        Common.Logging.ILog log = Common.Logging.LogManager.GetCurrentClassLogger();
        #region Properties

        public DateTime? lastHeartbeat = null;

        public DateTime LastHeartbeat
        {
            get
            {
                if (lastHeartbeat == null)
                {
                    lastHeartbeat = Helpers.Utils.CurrentServerUtcTime;
                }

                return lastHeartbeat.Value;
            }
        }

        private MachineInfo machineInfo = null;

        public MachineInfo MachineInfo
        {
            get
            {
                if (machineInfo == null)
                {
                    machineInfo = NPMonitor.Helpers.Utils.GetMachineInfo();
                }

                return machineInfo;
            }
        }

        #endregion

        #region Constructors

        public HeartbeatJob()
            : this(null)
        {
        }

        public HeartbeatJob(MachineInfo machineInfo)
        {
            this.machineInfo = machineInfo;
        }

        #endregion

        #region IJob Members

        public bool Execute()
        {
            bool result = true;

            try
            {
                bool flag = StoreManager.Current.MachineStore.Heartbeat(MachineInfo.MachineName);

                if (flag)
                {
                    lastHeartbeat = Helpers.Utils.CurrentServerUtcTime;
                }
                else
                {
                    result = false;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                result = false;
            }

            return result;
        }

        #endregion
    }
}
